<template>
  <a-select
    ref="selectRef"
    v-model="selectValue"
    :options="optionsList"
    :field-names="{ label: 'shelveCode', value: 'shelveCode' }"
    @click="handleClick"
    @change="selectChange"
    @search="handleSearch"
    style="width: 100%; height: 100%"
    allow-search
    allow-clear
  />
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue'
  import { post } from '@/api/http'
  import { ElMessage } from 'element-plus'
  import emitter from '@/hooks/useEventBus'
  emitter.on('pending-warehouseId', (warehouseId: any) => {
    wareId.value = warehouseId
  })
  const props = withDefaults(defineProps<{ params: any }>(), { params: {} })
  const { url } = props.params
  const selectRef = ref<any>(null)
  const selectValue = ref(props.params.value)
  const optionsList = ref([])
  const wareId = ref(localStorage.getItem('pending-warehouseId') || '')
  watch(
    () => wareId.value,
    (newVal: any) => {
      if (!newVal) {
        selectValue.value = ''
        optionsList.value = []
        props.params.changeVal({
          shelveCode: '',
          id: '',
        })
      }
    }
  )
  const selectChange = (val: any) => {
    selectValue.value = val
    const obj = optionsList.value.find((item: any) => item.shelveCode == val)
    if (obj) props.params.changeVal(obj)
  }
  const getSelectOptions = async (url: string, shelveCode: string) => {
    try {
      const res = await post({
        url,
        data: {
          warehouseId: wareId.value,
          shelveCode,
        },
      })
      if (res.code == 200) {
        optionsList.value = res.data
      } else {
        ElMessage.error(res.msg)
      }
    } catch (e) {
      console.log(e)
    }
  }
  const handleSearch = (val: any) => {
    getSelectOptions(url, val)
  }
  const handleClick = () => {
    if (!wareId.value) {
      ElMessage.warning('请选择仓库')
      return
    }
    getSelectOptions(url, '')
  }
</script>

<style lang="scss" scoped></style>
